#!/bin/bash

VAR_APP="example"


# ------------------------------------------------------
function djangorunserver {
    echo "启动Django 项目 [$VAR_APP]"
    echo "如需启动别的项目，请修改run.sh"
    echo "访问 http://127.0.0.1:8080"
    python3_check
    source ./venv/bin/activate
    dockerrunredis
    python apps/manage.py runserver 0.0.0.0:8080
    echo -en
}

function dockercompose {
    docker_install
    echo "正在构建本地Docker容器，构建完成后启动容器"
    echo "第一次构建大概要15分钟左右"
    docker stop djangoredis >> /dev/null 2>&1
    docker-compose up --build --force-recreate
    echo "访问 http://127.0.0.1"
    echo -en
}

function jenkinsbuild {
    echo "Jenkins 构建 暂未使用"
    echo -en
}

function initdjango {
    docker_install
    echo "正在拉取工程代码django+docker"
    git clone https://gitee.com/degao/docker-django.git temp
    cp -R temp/* ./
    rm -rf temp
    echo "正在建立venv虚拟环境,目录：venv"
    python3 -m venv venv
    echo "进入venv环境，安装django必要库"
    source ./venv/bin/activate
    pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
    echo "启动Django"
    djangorunserver
    echo -en
}
function initcreatesuperuser {
    echo "创建 Django Admin 的 用户名和密码"
    python ./apps/manage.py createsuperuser
    echo -en
}

function dockerrunredis {
  docker_install
  echo "通过 docker 启动本地 redis......"
  docker stop djangoredis >> /dev/null 2>&1
  docker run -it --rm -d -p 6379:6379 --name="djangoredis" redis:alpine
  echo "redis启动完毕"
  echo -en
}

function docker_install()
{
	echo "检查Docker......"
	docker -v
    if [ $? -eq  0 ]; then
        echo "检查到Docker已安装!"
    else
    	echo "安装docker环境..."
        curl -sSL https://get.daocloud.io/docker | sh
        echo "安装docker环境...安装完成!"
    fi
}

function python3_check()
{
	echo "检查Python3环境......"
	python3 -V
    if [ $? -eq  0 ]; then
        echo "Python3已安装!"
    else
        echo "未检测到 python3 环境"
        exit
#        curl -sSL https://get.daocloud.io/docker | sh
#        echo "安装docker环境...安装完成!"
    fi
}


function menu {
    clear
    echo
    echo -e "please select"
    echo -e "1. django runserver 0.0.0.0:8080"
    echo -e "2. docker-compose up --force-recreate (上线部署前执行)"
    echo -e "3. Jenkins build"
    echo -e "4. Init Django"
    echo -e "5. 创建Django超级管理员"
    echo -e "6. 本地启动配套 Redis，用于缓存"
    echo -e "0. Exit menu"
    echo -en "Enter an option: "
    read -n 1 option
}


if [[ $1 == "dev" ]]
then
  while [ 1 ]
  do
      menu
      case $option in
      0)
          break ;;
      1)
          djangorunserver ;;
      2)
          dockercompose ;;
      3)
          jenkinsbuild ;;
      4)
          initdjango ;;
      5)
          initcreatesuperuser ;;
      6)
          dockerrunredis ;;
      *)
          clear
          echo "Sorry, 重新选择" ;;
      esac
      echo -en "按任意键回到菜单"
      read -n 1 line
  done
  clear
fi


echo "启动Django 项目 [$VAR_APP] 路径：apps/apps/$VAR_APP"
echo "如果需要启动别的项目，请修改run.sh"
echo "访问 http://127.0.0.1"
gunicorn -c gunicorn.conf.py apps.wsgi:application
exit
